#!/bin/bash

# 前后端自动打包脚本
# 作用：构建前端，集成到后端，打包后端，生成部署zip包

# 彩色输出函数
function log_info() {
    echo -e "\033[1;32m[INFO] $1\033[0m"
}

function log_error() {
    echo -e "\033[1;31m[ERROR] $1\033[0m"
}

function log_warn() {
    echo -e "\033[1;33m[WARN] $1\033[0m"
}

# 检查命令是否存在
function check_command() {
    if ! command -v $1 &> /dev/null; then
        log_error "$1 命令未找到，请安装后再运行此脚本"
        exit 1
    fi
}

# 设置目录路径
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
FRONTEND_DIR="$SCRIPT_DIR/we_ai_front"
BACKEND_DIR="$SCRIPT_DIR/we_ai_back"
DEPLOY_DIR="$SCRIPT_DIR/deploy"
TEMP_DIR="$DEPLOY_DIR/we_ai_portal"
CONF_DIR="$DEPLOY_DIR/we_ai_portal/conf"
SHELL_DIR="$DEPLOY_DIR/we_ai_portal/bin"
LIB_DIR="$DEPLOY_DIR/we_ai_portal/lib"
LOG_DIR="$DEPLOY_DIR/we_ai_portal/logs"

# 检查必要工具
log_info "检查环境..."
check_command node
check_command npm
check_command java
check_command mvn
check_command 7z

# 创建部署目录
mkdir -p "$DEPLOY_DIR"
mkdir -p "$TEMP_DIR"
mkdir -p "$CONF_DIR"
mkdir -p "$SHELL_DIR"
mkdir -p "$LIB_DIR"
mkdir -p "$LOG_DIR"

# 步骤1: 构建前端
log_info "开始构建前端项目..."
cd "$FRONTEND_DIR" || { log_error "前端目录不存在: $FRONTEND_DIR"; exit 1; }

log_info "删除node_modules..."
rm -rf node_modules

log_info "安装前端依赖..."
npm install || { log_error "安装前端依赖失败"; exit 1; }

log_info "构建前端项目..."
npm run build || { log_error "前端构建失败"; exit 1; }

if [ ! -d "dist" ]; then
    log_error "前端构建产物目录不存在，构建可能失败"
    exit 1
fi

log_info "前端构建成功！"

# 步骤2: 集成前端到后端
log_info "集成前端到后端..."
cd "$BACKEND_DIR" || { log_error "后端目录不存在: $BACKEND_DIR"; exit 1; }

rm -rf src/main/resources/static

# 确保静态资源目录存在
mkdir -p "src/main/resources/static"

# 复制前端构建产物到后端
log_info "复制前端文件到后端静态资源目录..."
cp -r "$FRONTEND_DIR/dist/"* "src/main/resources/static/" || { log_error "复制前端文件失败"; exit 1; }

# 步骤3: 构建后端
log_info "开始构建后端项目..."
mvn clean package -DskipTests || { log_error "后端构建失败"; exit 1; }

if [ ! -f "target/we-ai-back-0.0.1-SNAPSHOT.jar" ]; then
    log_error "后端构建产物不存在，构建可能失败"
    exit 1
fi

log_info "后端构建成功！"

# 步骤4: 创建部署包
log_info "创建部署包..."

# 复制JAR文件到部署目录
log_info "复制JAR包..."
cp "target/we-ai-back-0.0.1-SNAPSHOT.jar" "$LIB_DIR" || { log_error "复制JAR文件失败"; exit 1; }


# 复制配置文件从resources目录
log_info "复制配置文件..."
cp "src/main/resources/application.properties" "$CONF_DIR" || { log_error "复制配置文件失败"; exit 1; }
# 复制logback配置文件（如果存在）
if [ -f "src/main/resources/logback-spring.xml" ]; then
    cp "src/main/resources/logback-spring.xml" "$CONF_DIR" || { log_error "复制logback配置文件失败"; exit 1; }
fi


log_info "复制启动停止文件..."
cp "script/start.sh" "$SHELL_DIR" || { log_error "复制start文件失败"; exit 1; }
cp "script/stop.sh" "$SHELL_DIR" || { log_error "复制stop文件失败"; exit 1; }

# 打包部署文件
log_info "创建zip部署包..."
cd "$DEPLOY_DIR" || { log_error "部署目录不存在"; exit 1; }
7z a we_ai_portal_deploy.zip we_ai_portal/ || { log_error "创建zip包失败"; exit 1; }

# 完成
log_info "部署包创建成功: $DEPLOY_DIR/we_ai_portal_deploy.zip"
log_info "脚本执行完毕！"